<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>科室列表</title>
    <script src="/static/med_booking/js/vue.js"></script>
    <script src="/static/med_booking/js/axios.js"></script>
    <!-- 引入element组件库 -->
    <script src="/static/med_booking/js/index.js"></script>
    <link rel="stylesheet" href="/static/med_booking/css/index.css">
</head>

<body>
<div id="app">
    <el-button type="primary" @click="showAddDialog">新增科室</el-button>
    <el-input v-model="input" placeholder="请输入内容" stripe style="width: auto;"
              @keyup.enter.native="search"></el-input>
    <el-button type="primary" @click="search">搜索</el-button>
    <el-table :data="departments" stripe style="width: 100%" v-loading="loading">
        <el-table-column prop="depId" label="编号" width="180"></el-table-column>
        <el-table-column prop="depName" label="科室名称" width="180"></el-table-column>
        <el-table-column prop="description" label="描述"></el-table-column>
        <el-table-column label="状态">
            <template slot-scope="scope">
                <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0"
                           @change="handleStatusChange(scope.row)">
                </el-switch>
                <span style="margin-left: 10px">{{ scope.row.status === 1 ? '启用' : '禁用' }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间"></el-table-column>
        <el-table-column prop="updatedAt" label="修改时间"></el-table-column>
        <el-table-column label="操作">
            <template slot-scope="scope">
                <el-button size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
                <el-button size="mini" type="danger" @click="remove(scope.row.depId, scope.$index)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <el-pagination background layout="prev, pager, next" :page-size="pageSize" :current-page="currentPage"
                   :total="total" @current-change="handleCurrentChange">
    </el-pagination>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
        <el-form :model="form" :rules="rules" ref="form" label-width="100px">
            <el-form-item label="科室名称" prop="depName">
                <el-input v-model="form.depName"></el-input>
            </el-form-item>
            <el-form-item label="描述" prop="description">
                <el-input type="textarea" v-model="form.description"></el-input>
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-switch v-model="form.status" :active-value="1" :inactive-value="0">
                </el-switch>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </span>
    </el-dialog>
</div>
<script>
    // 配置axios默认设置
    axios.defaults.baseURL = 'http://localhost:8080';
    axios.defaults.headers.common['Content-Type'] = 'application/json';

    var app = new Vue({
        el: "#app",
        data: {
            input: '',
            departments: [],
            originalDepartments: [], // 新增，用于保存原始数据
            loading: false,
            currentPage: 1,       // 当前页码
            pageSize: 10,        // 每页显示条数
            total: 0,            // 总数据量
            dialogVisible: false,
            dialogTitle: '新增科室',
            form: {
                depId: null,
                depName: '',
                description: '',
                status: 1
            },
            rules: {
                depName: [
                    { required: true, message: '请输入科室名称', trigger: 'blur' }
                ]
            },
            isEdit: false
        },
        methods: {
            getDepartment() {
                this.loading = true;
                axios.get("http://localhost:8080/department")
                    .then((res) => {
                        this.originalDepartments = res.data;
                        this.total = res.data.length;
                        this.updatePageData(); // 更新当前页数据
                        this.loading = false;
                    })
                    .catch((error) => {
                        console.error('加载数据失败:', error);
                        this.$message.error('加载科室数据失败');
                        this.loading = false;
                    });
            },
            //搜索
            search() {
                if (!this.input.trim()) {
                    // 如果搜索框为空，显示所有数据
                    this.originalDepartments = [...this.departments];
                    this.total = this.originalDepartments.length;
                    this.currentPage = 1; // 重置到第一页
                    this.updatePageData();
                    return;
                }

                // 过滤数据，匹配科室名称或描述
                const filtered = this.originalDepartments.filter(dep => {
                    return (
                        dep.depName.includes(this.input) ||
                        (dep.description && dep.description.includes(this.input))
                    );
                });

                this.total = filtered.length;
                this.currentPage = 1; // 搜索后重置到第一页
                this.departments = filtered.slice(0, this.pageSize);
            },
            //更新分页
            updatePageData() {
                const start = (this.currentPage - 1) * this.pageSize;
                const end = start + this.pageSize;
                this.departments = this.originalDepartments.slice(start, end);
            },
            //处理分页
            handleCurrentChange(page) {
                this.currentPage = page;
                this.updatePageData();
            },
            //修改状态
            handleStatusChange(dep) {
                //发送请求，当我们的请求对数据库中的数据有修改的情况下，用post
                //需要传递两个参数，一个是需要修改的数据的id，一个是状态值
                console.log(dep)
                let params = {
                    depId: dep.depId,
                    status: dep.status
                }
                axios.post('http://localhost:8080/department/updateStatus', params)
                    .then((res) => {
                        if (res.data == true) {
                            this.getDepartment();

                        }
                    })
                    .catch((error) => {
                        console.error('状态更新失败:', error);
                        this.$message.error('状态更新失败');
                        // 恢复原状态
                        row.status = row.status === 1 ? 0 : 1;
                    });
            },
            showAddDialog() {
                this.dialogTitle = '新增科室';
                this.isEdit = false;
                // 获取当前时间作为默认值
                const now = new Date().toISOString();
                this.form = {
                    depId: null,
                    depName: '',
                    description: '',
                    status: 1,
                    createdAt: now,  // 新增时设置创建时间
                    updatedAt: now   // 新增时也设置更新时间
                };
                if (this.$refs.form) {
                    this.$refs.form.clearValidate();
                }
                this.dialogVisible = true;
            },

            showEditDialog(row) {
                this.dialogTitle = '编辑科室';
                this.isEdit = true;
                // 深拷贝行数据，同时确保时间字段存在
                this.form = JSON.parse(JSON.stringify(row));
                // 编辑时只更新updatedAt
                this.form.updatedAt = new Date().toISOString();
                this.dialogVisible = true;
            },
            submitForm() {
                this.$refs.form.validate((valid) => {
                    if (valid) {
                        if (this.isEdit) {
                            axios.put(`/department/${this.form.depId}`, this.form)
                                .then(() => {
                                    this.$message.success('更新成功');
                                    this.getDepartment();
                                    this.dialogVisible = false;
                                })
                                .catch(error => {
                                    console.error('更新失败:', error);
                                    this.$message.error('更新失败');
                                });
                        } else {
                            axios.post("/department", this.form)
                                .then(() => {
                                    this.$message.success('新增成功');
                                    this.getDepartment();
                                    this.dialogVisible = false;
                                })
                                .catch(error => {
                                    console.error('新增失败:', error);
                                    this.$message.error('新增失败');
                                });
                        }
                    } else {
                        return false;
                    }
                });
            },
            remove(depId, index) {
                this.$confirm('确定要删除这条记录吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.delete(`/department/${depId}`)
                        .then((res) => {
                            this.getDepartment();
                        })
                }).catch(() => {
                    this.$message.info('已取消删除');
                });
            }
        },
        mounted() {
            this.getDepartment();
        }
    })
</script>
</body>

</html>